package edu.hawaii.halealohacli.command;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * Defines the rank-towers command for hale-aloha-cli-chair.
 * 
 * @author Chris Fang
 */
public class RankTowers implements Command {

  private WattDepotClient client;
  private String name;
  private String usage;
  private String description;
  private SourceData dataModule;
  private String startDateFromUser;
  private String endDateFromUser;
  private String errorMsg;
  private List<SourceData> sources;

  /**
   * Creates an instance of this command with the client set to null by default, requiring
   * initialization.
   */
  public RankTowers() {
    this.name = "rank-towers";
    this.usage = "rank-towers [start] [end]";
    this.description =
        "Returns a list in sorted order from least to most energy consumed"
            + "between the [start] and [end] date (yyyy-mm-dd)";
    this.errorMsg = "The date %s is invalid " + "(Enter \"help\" to see command usage)";
  }

  /**
   * Initializes this command with a healthy WattDepot client.
   * 
   * @param client A healthy WattDepot client used to initialize the command
   * @param args Arguments required by the command for execution
   * @return Whether or not the arguments passed was accepted by the command initialization
   */
  @Override
  public boolean initializeCommand(WattDepotClient client, String[] args) {
    this.client = client;
    if (args.length != 3) {
      System.out.format("The arguments are invalid " + "(Enter \"help\" to see command usage)");
      return false;
    }
    this.startDateFromUser = args[1];
    this.endDateFromUser = args[2];
    return true;
  }

  /**
   * Returns the name of this command.
   * 
   * @return the name of this command
   */
  @Override
  public String getName() {
    return this.name;
  }

  /**
   * Returns the usage syntax of this command.
   * 
   * @return the usage syntax of this command
   */
  @Override
  public String getUsage() {
    return this.usage;
  }

  /**
   * Returns the description of this command.
   * 
   * @return a description of this command
   */
  @Override
  public String getDescription() {
    return this.description;
  }

  /**
   * Initialize the SouceData with the energy data obtained from the client.
   * 
   * @param startDate The starting date from which to gather energy consumption data from
   * @param endDate The ending date from which to gather energy consumption data from
   * @return Whether or not the data was successfully initialized
   */
  public boolean initializeData(String startDate, String endDate) {
    try {
      List<Source> originalList = client.getSources();
      sources = new ArrayList<SourceData>();
      Calendar startTime = getTime(startDate);
      if (startTime == null) {
        System.out.format(errorMsg, startDate);
        return false;
      }
      Calendar endTime = getTime(endDate);
      if (endTime == null) {
        System.out.format(errorMsg, endDate);
        return false;
      }
      endTime.add(Calendar.HOUR, 24);
      for (Source source : originalList) {
        if (!source.getName().contains("-")) {
          dataModule = new SourceData(source.getName());
          dataModule.setEnergyConsumed(client.getEnergyConsumed(source.getName(),
              toXMLGregorianCalendar(startTime), toXMLGregorianCalendar(endTime), 15));
          sources.add(dataModule);
        }
      }
      return true;
    }
    catch (NotAuthorizedException e) {
      System.out.format("You are not authorized to view %s", name);
      return false;
    }
    catch (ResourceNotFoundException e) {
      System.out.format("The tower or lounge %s is invalid "
          + "(Enter \"help\" to see available sources", name);
      return false;
    }
    catch (BadXmlException e) {
      System.out.format("Bad XML: %s", e.getMessage());
      return false;
    }
    catch (MiscClientException e) {
      System.out.format("Unknown error has occurred: %s", e.getMessage());
      return false;
    }
  }

  /**
   * Try to convert a String representation of a date into a Calendar representation.
   * 
   * @param date String representation of a date
   * @return A Calendar representation for the input date or NULL if the date was invalid
   */
  protected Calendar getTime(String date) {
    Calendar inputDate = GregorianCalendar.getInstance();
    Calendar today = GregorianCalendar.getInstance();
    Date convertedDate = convertDate(date);
    if (convertedDate == null) {
      return null;
    }
    inputDate.setTime(convertedDate);
    if (inputDate.compareTo(today) <= 0) {
      return inputDate;
    }
    else {
      return null;
    }
  }

  /**
   * Try to convert a String representation into a Date object.
   * 
   * @param date String representation of a date
   * @return A Date object for the input date or NULL if the conversion was unsuccessful
   */
  protected Date convertDate(String date) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    try {
      Date parsedDate = formatter.parse(date);
      if (!formatter.format(parsedDate).equals(date)) {
        System.out.format(errorMsg, date);
        return null;
      }
      return parsedDate;

    }
    catch (Exception e) {
      System.out.format(errorMsg, date);
      return null;
    }
  }

  /**
   * Prints the results of executing this command.
   */
  @Override
  public void printResults() {
    if (!initializeData(this.startDateFromUser, this.endDateFromUser)) {
      return;
    }
    Collections.sort(sources, SourceData.sortEnergyConsumed);
    System.out.format("For the interval %s to %s, energy consumption by towers were:",
        startDateFromUser, endDateFromUser);
    for (SourceData source : sources) {
      System.out.format("%n%-10s %.1f kWh", source.getName(),
          source.getEnergyConsumed() / 1000);
    }
  }

  /**
   * Converts a calendar object into a XMLGregorianCalendar object.
   * 
   * @param date The Calendar object to be converted
   * @return The converted XMLGregorianCalendar object
   */
  protected XMLGregorianCalendar toXMLGregorianCalendar(Calendar date) {
    GregorianCalendar calendar = (GregorianCalendar) date;
    try {
      DatatypeFactory converter = DatatypeFactory.newInstance();
      return converter.newXMLGregorianCalendar(calendar);
    }
    catch (DatatypeConfigurationException e) {
      System.out.format("There was a problem in the date conversion: " + e.getMessage());
      return null;
    }
  }

}
